# -*- coding: utf-8 -*-
import os.path
from mimetypes import guess_type
from django.http import HttpResponse, Http404
from pyhost.sha1storage.models import SHA1FilesRealname
from django.conf import settings

def get_real_filename(request):
	if request.method == "POST":
		name = request.POST.get("filename", "")
	if request.method == "GET":
		name = request.GET.get("filename", "")
	try:
		realname = SHA1FilesRealname.objects.get(username=name)
		rl = realname.realname
		if not rl.startswith("/"):
			rl = "/"+rl
		
		mime = guess_type(name)

	except:
		if os.path.exists(os.path.join(settings.MEDIA_ROOT, name)):
			rl = name
			if not rl.startswith("/"):
				rl = "/"+rl
			mime = guess_type(name)
		else:
			raise Http404
	
	response = HttpResponse()
	if mime:
		response['Content-type'] = 	mime[0]
	if not mime[0].startswith("image/"):
		response['Content-Disposition'] = "attachment"

	response['X-Accel-Redirect'] = rl
	return response
